import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/register', component: () => import('@/views/Register.vue') },
  { path: '/detail/:id', component: () => import('@/views/Detail.vue') },
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      { path: 'article', component: () => import('@/views/Layout/Article.vue') },
      { path: 'collect', component: () => import('@/views/Layout/Collect.vue') },
      { path: 'like', component: () => import('@/views/Layout/Like.vue') },
      { path: 'user', component: () => import('@/views/Layout/User.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

export default router

// 前置导航守卫
// 必须在创建router之后，导出之前，加入全局前置导航守卫
router.beforeEach((to, from, next) => {
  // console.log(to) // to.path 表示跳转的路由地址
  // next()
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else {
    // 访问面经列表页、详情页、收藏页......，还需要判断是否有token
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})
